﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace WebApplication1
{
    /// <summary>
    /// 微信验证使用ashx方式实现
    /// </summary>
    public class Handler1 : IHttpHandler, IRequiresSessionState
    {
       

        public void ProcessRequest(HttpContext context)
        {
            string url = context.Request.RawUrl;

            if (context.Request.HttpMethod != "POST")
            {
                ValidUrl("duanshaoyan");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }



        public static string VqiRequest(string key)
        {
            return HttpContext.Current.Request.QueryString[key].ToString();
        }

        /// <summary>
        /// 验证url权限， 接入服务器
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static bool ValidUrl(string token)
        {
            string echoStr = VqiRequest("echoStr");
            if (CheckSignature(token))
            {
                if (!string.IsNullOrEmpty(echoStr))
                {
                    ResponseWrite(echoStr); 
                    return true;
                }

            }
            return false;
        }

        /// <summary>
        /// 验证微信签名
        /// </summary>
        /// * 将token、timestamp、nonce三个参数进行字典序排序
        /// * 将三个参数字符串拼接成一个字符串进行sha1加密
        /// * 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信。
        /// <returns></returns>
        public static bool CheckSignature(string token)
        {
            string signature = VqiRequest("signature");
            string timestamp = VqiRequest("timestamp");
            string nonce = VqiRequest("nonce");
            string[] ArrTmp = { token, timestamp, nonce };
            Array.Sort(ArrTmp);     //字典排序
            string tmpStr = string.Join("", ArrTmp);
            tmpStr = HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            tmpStr = tmpStr.ToLower();
            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 根据指定的密码和哈希算法生成一个适合于存储在配置文件中的哈希密码
        /// </summary>
        /// <param name="str">要进行哈希运算的密码</param>
        /// <param name="type"> 要使用的哈希算法</param>
        /// <returns>经过哈希运算的密码</returns>
        public static string HashPasswordForStoringInConfigFile(string str, string type)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, type);
        }

        public static void ResponseWrite(string str)
        {
            HttpContext.Current.Response.Write(str);
            HttpContext.Current.Response.End();
        }
    }
}